package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.List;


@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public void delete(long id) {
        employeeMapper.deleteById(id);
        employeeMapper.deleteEmployeeAndRoleRelation(id);
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectList(null);
    }

    @Override
    public void saveOrUpdate(Employee employee,Long[] ids) {
        if(employee.getId() == null){
            employeeMapper.insert(employee);
        }else{
            employeeMapper.updateByPrimaryKey(employee);
            employeeMapper.deleteEmployeeAndRoleRelation(employee.getId());
        }
        if(ids!=null){
            for (Long roleId : ids) {
                employeeMapper.insertEmployeeAndRoleRelation(employee.getId(),roleId);

            }
        }

    }

    @Override
    public PageResult query(QueryObject qo) {
        int row = employeeMapper.selectForCount(qo);
        if(row == 0){
            return PageResult.EMPTY_PAGE;
        }
        List<Employee> data = employeeMapper.selectForList(qo);
        return new PageResult(qo.getCurrentPage(),qo.getPageSize(),data,row);
    }

    @Override
    public void login(String username, String password) {
        Employee employee = employeeMapper.selectByUsernameAndPassword(username,password);
        if(employee == null){
            throw new RuntimeException("账号或密码不正确");
        }

        UserContext.setCurrent(employee);

        List<String> expressions = permissionMapper.selectALlExpressionsByEmployeeId(employee.getId());

        UserContext.setExpressions(expressions);
    }
}
